class ProjectController < ApplicationController
  require_role "project_admin", :only => [:new, :create, :edit, :update]
  layout 'ipm'
  
  def index
    redirect_to :action => 'list'
  end
  
  def list
    #@projects = Project.find(:all, :order => 'name DESC')
    @projects = current_user.active_projects
    
    #page title
    @header_title = 'Projects'
    #sub menu
    @submenu = 'project'
  end
  
  def list_active
    #@projects = Project.find(:all, :order => 'name DESC')
    @projects = current_user.projects
    
    #page title
    @header_title = 'Projects'
    #sub menu
    @submenu = 'project'
    render :action => 'list'
  end
  
  def show
    @project = Project.find(params[:project])
    
    #page info
    @title = @project.name
    #page title
    @header_title = @project.name
    #sub menu
    @submenu = 'ticket'
    
    #login check
    if not (current_user.has_role?(@project.name + "_member") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end
    
    
    if params[:list_type].empty?
      params[:list_type] = 'active'
    end
      session[:list_type] = params[:list_type]
    
    sort = sort_helper(params[:sort], ['id', 'name', 'status', 'priority', 'ticket_type', 'owner_id', 'user_id', 'updated_at', 'end_date', 'hours'])
    session[:list_sort] = params[:sort]
    
    
    conditions = search_helper(params[:search_query], ['name','id'])
    
    conditions = list_type_helper(params[:list_type], conditions)
    if !conditions[0].empty?
      conditions[0] += " AND project_id = "+ @project.id.to_s
    end
    
    @tickets = Ticket.find(:all, :conditions => conditions, :order => sort)
    
    if request.xhr? # ajax
      render :partial => 'show_list_ajax', :layout => false
    end
    
    
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  rescue ActiveRecord::StatementInvalid
    @project = Project.find(params[:project])
    @tickets = Ticket.find(:all, :conditions => [ "project_id = ?", @project])
  end
  
  
  
  
  
  def new
    @project = Project.new
    
    #page title
    @header_title = 'New Project'
    #sub menu
    @submenu = 'project'
  end
  
  def create
    
    #page title
    @header_title = 'New Project'
    #sub menu
    @submenu = 'project'
    
    
    if request.get?
      redirect_to :action => 'new'
    else
      @project = Project.new(params[:project])
             
      params[:categories] = [] if params[:categories].nil?
      categories = params[:categories].collect { |i| Category.find(i) }
      @project.categories = categories
         
      if @project.save
        role_member = Role.new()
        role_member.name = @project.name + '_member'
        role_member.save

        role_admin = Role.new()
        role_admin.name = @project.name + '_admin'
        role_admin.save
        
        flash[:notice] = "Project was created successfully."
        redirect_to :action => 'show', :project => @project
      else
        render :action => 'new'
      end
    end
  end
  
  
  def edit
  
    #page title
    @header_title = 'Edit Project'
    #sub menu
    @submenu = 'project'
      
  
    @project = Project.find(params[:project])
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  end
  
  def update
    
    #page title
    @header_title = 'Edit Project'
    #sub menu
    @submenu = 'project'
    
     if request.get?
        redirect_to :action => 'list'
      else
        @project = Project.find(params[:project_id])
        
        role_member = Role.find_by_name(@project.name + '_member')
        role_admin = Role.find_by_name(@project.name + '_admin')
        
        @project.update_attributes(params[:project])
        
        role_member.name = @project.name + '_member'
        role_admin.name = @project.name + '_admin'
        
        params[:categories] = [] if params[:categories].nil?
        categories = params[:categories].collect { |i| Category.find(i) }
        @project.categories = categories
        
        if @project.save
          
          role_member.save
          role_admin.save
          
          flash[:notice] = "Project was updated successfully."
          redirect_to :action => 'show', :project => @project
        else
          render :action => 'edit'
        end  
      end
  end
  
  
  
  def userlist
    @project = Project.find(params[:project])
    @title = @project.name + "::Userlist"
      #page title
      @header_title = @project.name
      #sub menu
      @submenu = 'ticket'
      
    if not (current_user.has_role?(@project.name + "_member") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end
    
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  end
  
  def edit_userlist
    @project = Project.find(params[:project])
    @title = @project.name + "::Edit Userlist"
      #page title
      @header_title = @project.name
      #sub menu
      @submenu = 'ticket'
    if not (current_user.has_role?("project_admin") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end

  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  end
  
  def delete_member
    @project = Project.find(params[:project])
    
    if not (current_user.has_role?("project_admin") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end
    user = User.find(params[:member])
    user.roles.delete(Role.find_by_name(@project.name + "_member"))
    
    edit_userlist
    render :partial =>'edit_userlist_partial'
  end
  
  def close
    @project = Project.find(params[:project])
    
    if not (current_user.has_role?("project_admin") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end
    
    @project.active = false
    @project.save
    flash[:notice] = "Project has been closed."
    redirect_to :action => 'list'
  end
  
  def print
    @project = Project.find(params[:project])
    
    @title = @project.name + "::print"
    
    if not (current_user.has_role?(@project.name + "_member") || current_user.has_role?(@project.name + "_admin"))
      flash[:error] = "Forbidden"
      redirect_to :action => 'list'
    end
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  end
  
  def tag_list_big
    @project = Project.find(params[:project])
    @tags = Ticket.tag_counts(:order => 'count desc', :conditions => ["Taggings.taggable_id IN (SELECT id FROM tickets WHERE project_id=" + @project.id.to_s + ")"])
    
    if request.xhr? # ajax
      render :partial => 'tag_list', :layout => false
    end
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Could not find project with ID=" + params[:project].to_s
    redirect_to :action => 'list'
  end
  
  def tag_list_small
     @project = Project.find(params[:project])
     @tags = Ticket.tag_counts(:limit => 4 , :order => 'count desc', :conditions => ["Taggings.taggable_id IN (SELECT id FROM tickets WHERE project_id=" + @project.id.to_s + ")"])

     if request.xhr? # ajax
       render :partial => 'tag_list', :layout => false
     end
   rescue ActiveRecord::RecordNotFound
     flash[:notice] = "Could not find project with ID=" + params[:project].to_s
     redirect_to :action => 'list'
   end
   
   def tag_list
      @project = Project.find(params[:project])

      @title = @project.name + "::tags"
       #page title
        @header_title = @project.name
        #sub menu
        @submenu = 'ticket'

      if not (current_user.has_role?(@project.name + "_member") || current_user.has_role?(@project.name + "_admin"))
        flash[:error] = "Forbidden"
        redirect_to :action => 'list'
      end
    end
    
   def tag
     @project = Project.find(params[:project])
     @tag = Tag.find_by_name(params[:tag])
     
     
     conditions = tag_search_helper(params[:search_query], ['tickets.name','tickets.id'])
     sort = sort_helper(params[:sort], ['id', 'name', 'status', 'priority', 'ticket_type', 'owner_id', 'user_id', 'updated_at'])
     
     #@tickets = @project.tickets().find_tagged_with(@tag.name)
     sql = "SELECT DISTINCT tickets.* FROM tickets  INNER JOIN taggings tickets_taggings ON tickets_taggings.taggable_id = tickets.id AND tickets_taggings.taggable_type = 'Ticket' INNER JOIN tags tickets_tags ON tickets_tags.id = tickets_taggings.tag_id WHERE ((tickets.project_id = " + @project.id.to_s + ") AND (tickets_tags.name LIKE '" + @tag.name + "') AND " + conditions[0] + ")"
     if not sort.nil?
       sql = sql + "ORDER BY " + sort;
     end
     @tickets = Ticket.find_by_sql( sql)
      #@tcket = Ticket.find(:all,
      #  :joins => "INNER JOIN taggings tickets_taggings ON tickets_taggings.taggable_id = tickets.id AND tickets_taggings.taggable_type = 'Ticket' " +
      #            "INNER JOIN tags tickets_tags ON tickets_tags.id = tickets_taggings.tag_id", :group => 'tickets.id')
        
     @title = @project.name + "::tag->" + @tag.name
      #page title
       @header_title = @project.name
       #sub menu
       @submenu = 'ticket'

     if not (current_user.has_role?(@project.name + "_member") || current_user.has_role?(@project.name + "_admin"))
       flash[:error] = "Forbidden"
       redirect_to :action => 'list'
     end
     
     if request.xhr? # ajax
       render :partial => 'show_list_ajax', :layout => false
     end
     
   rescue ActiveRecord::RecordNotFound
     flash[:notice] = "Could not find project with ID=" + params[:project].to_s
     redirect_to :action => 'list'
   rescue ActiveRecord::StatementInvalid
     @project = Project.find(params[:project])
     @tickets = @project.tickets().find_tagged_with(@tag.name)
   end
end
